package com.suyl.redisbf.utils;

import io.rebloom.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisException;

/**
 * redis布隆过滤器
 */
public class JedisUtils {

    private static Logger logger = LoggerFactory.getLogger(JedisUtils.class);

    private static JedisPool jedisPool = null;

    public static final String KEY_PREFIX = "gzskjt";

    /**
     * 获取资源
     *
     * @return
     * @throws JedisException
     */
    public static Jedis getResource() throws JedisException {
        Jedis jedis = null;
        try {
            if (jedisPool == null) {

                JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
                jedisPoolConfig.setMaxIdle(10);
                jedisPoolConfig.setMaxTotal(100);
                jedisPoolConfig.setMaxWaitMillis(3000);

                jedisPool = new JedisPool(jedisPoolConfig, "192.168.59.59", 6379, 3000, "123456");
            }
            jedis = jedisPool.getResource();
            // logger.debug("getResource.", jedis);
        } catch (JedisException e) {
            logger.warn("getResource.", e);
            throw e;
        }
        return jedis;
    }

    public static void main(String[] args) {
        getResource();
        String userIdBloomKey = "userid";
        // 创建客户端，jedis实例
        Client client = new Client(jedisPool);
        // 创建一个有初始值和出错率的过滤器
//        client.createFilter(userIdBloomKey, 100000, 0.01);
        // 新增一个<key,value>
        boolean userid1 = client.add(userIdBloomKey, "101310222");
        System.out.println("userid1 add " + userid1);

        // 批量新增values
        boolean[] booleans = client.addMulti(userIdBloomKey, "101310111", "101310222", "101310222");
        System.out.println("add multi result " + booleans);

        // 某个value是否存在
        boolean exists = client.exists(userIdBloomKey, "101310111");
        System.out.println("101310111 是否存在" + exists);

        //某批value是否存在
        boolean existsBoolean[] = client.existsMulti(userIdBloomKey, "101310111", "101310222", "101310222", "11111111");
        System.out.println("某批value是否存在 " + existsBoolean);

        client.addMulti(userIdBloomKey, "suyanlong", "candy", "kongzhaojun");

        existsBoolean = client.existsMulti(userIdBloomKey, "suyanlong", "candy", "kongzhaojun", "suyanlong1111", "candy", "kongzhaojun");

        for (boolean b : existsBoolean) {
            System.out.println(b);
        }
    }
}
